// 日志级别
export enum LogLevel {
  INFO = "INFO",
  WARN = "WARN",
  ERROR = "ERROR",
}

// 日志接口
export interface LogEntry {
  id: string;
  timestamp: string;
  level: LogLevel;
  message: string;
  duration?: number;
  userId?: string;
  username?: string;
  ip?: string;
  userAgent?: string;
  requestUrl?: string;
  requestMethod?: string;
  requestBody?: any;
  responseStatus?: number;
  responseBody?: any;
  error?: any;
}

// 日志管理器
class Logger {
  private logs: LogEntry[] = [];
  private maxLogs = 1000; // 最大日志数量

  // 生成唯一ID
  private generateId(): string {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  }

  // 记录日志
  log(level: LogLevel, message: string, data?: Partial<LogEntry>): void {
    const logEntry: LogEntry = {
      id: this.generateId(),
      timestamp: new Date().toISOString(),
      level,
      message,
      ...data,
    };

    this.logs.unshift(logEntry);

    // 限制日志数量
    if (this.logs.length > this.maxLogs) {
      this.logs = this.logs.slice(0, this.maxLogs);
    }

    // 控制台输出
    console.log(`[${level}] ${message}`, data || "");

    // 发送到服务器（可选）
    this.sendToServer(logEntry);
  }

  // 信息日志
  info(message: string, data?: Partial<LogEntry>): void {
    this.log(LogLevel.INFO, message, data);
  }

  // 警告日志
  warn(message: string, data?: Partial<LogEntry>): void {
    this.log(LogLevel.WARN, message, data);
  }

  // 错误日志
  error(message: string, error?: any, data?: Partial<LogEntry>): void {
    this.log(LogLevel.ERROR, message, { ...data, error });
  }

  // 获取日志
  getLogs(level?: LogLevel, limit?: number): LogEntry[] {
    let filteredLogs = this.logs;

    if (level) {
      filteredLogs = filteredLogs.filter((log) => log.level === level);
    }

    if (limit) {
      filteredLogs = filteredLogs.slice(0, limit);
    }

    return filteredLogs;
  }

  // 清空日志
  clear(): void {
    this.logs = [];
  }

  // 发送日志到服务器
  private async sendToServer(logEntry: LogEntry): Promise<void> {
    try {
      // 这里可以调用API将日志发送到服务器
      // 暂时注释掉，避免未使用的参数警告
      console.log("Log entry ready to send:", logEntry);
      // await fetch('/api/logs', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify(logEntry)
      // });
    } catch (error) {
      console.error("Failed to send log to server:", error);
    }
  }
}

// 创建全局日志实例
export const logger = new Logger();

// 请求拦截器 - 记录API请求
export const createRequestLogger = () => {
  return {
    request: (config: any) => {
      const startTime = Date.now();

      // 记录请求开始
      logger.info("API Request Started", {
        requestUrl: config.url,
        requestMethod: config.method,
        requestBody: config.data,
        timestamp: new Date().toISOString(),
      });

      // 添加响应拦截器来记录响应时间
      config.metadata = { startTime };

      return config;
    },

    response: (response: any) => {
      const endTime = Date.now();
      const duration = endTime - response.config.metadata.startTime;

      // 记录请求完成
      logger.info("API Request Completed", {
        requestUrl: response.config.url,
        requestMethod: response.config.method,
        responseStatus: response.status,
        responseBody: response.data,
        duration,
        timestamp: new Date().toISOString(),
      });

      return response;
    },

    error: (error: any) => {
      const endTime = Date.now();
      const duration = endTime - (error.config?.metadata?.startTime || endTime);

      // 记录请求错误
      logger.error("API Request Failed", error, {
        requestUrl: error.config?.url,
        requestMethod: error.config?.method,
        requestBody: error.config?.data,
        responseStatus: error.response?.status,
        responseBody: error.response?.data,
        duration,
        timestamp: new Date().toISOString(),
      });

      return Promise.reject(error);
    },
  };
};

// 性能监控
export class PerformanceMonitor {
  private metrics: Map<string, number[]> = new Map();

  // 记录性能指标
  recordMetric(name: string, value: number): void {
    if (!this.metrics.has(name)) {
      this.metrics.set(name, []);
    }
    this.metrics.get(name)!.push(value);

    // 只保留最近100个值
    const values = this.metrics.get(name)!;
    if (values.length > 100) {
      values.shift();
    }
  }

  // 获取性能指标统计
  getMetricStats(name: string): { avg: number; min: number; max: number; count: number } | null {
    const values = this.metrics.get(name);
    if (!values || values.length === 0) return null;

    const sum = values.reduce((a, b) => a + b, 0);
    const avg = sum / values.length;
    const min = Math.min(...values);
    const max = Math.max(...values);

    return { avg, min, max, count: values.length };
  }

  // 获取所有指标
  getAllMetrics(): Record<string, { avg: number; min: number; max: number; count: number }> {
    const result: Record<string, any> = {};
    for (const [name] of this.metrics) {
      const stats = this.getMetricStats(name);
      if (stats) {
        result[name] = stats;
      }
    }
    return result;
  }
}

// 创建全局性能监控实例
export const performanceMonitor = new PerformanceMonitor();
